package com.czl.module_service.fragment.assetUse

import com.alibaba.android.arouter.facade.annotation.Route
import com.czl.base.base.BaseFragment
import com.czl.base.config.AppConstants
import com.czl.base.data.bean.tengyun.CategoryBean
import com.czl.module_service.BR
import com.czl.module_service.R
import com.czl.module_service.adapter.asset.SortChooseListAdapter
import com.czl.module_service.databinding.FragmentSortChooseListBinding
import com.czl.module_service.extension.loadCompletedData
import com.czl.module_service.view.CategoryPopup
import com.czl.module_service.viewmodel.assetUse.SortChooseListViewModel
import com.lxj.xpopup.XPopup

@Route(path = AppConstants.Router.Service.F_SERVICE_SORT_CHOOSE_LIST)
class SortChooseListFragment :
    BaseFragment<FragmentSortChooseListBinding, SortChooseListViewModel>() {

    private val mAdapter: SortChooseListAdapter by lazy {
        SortChooseListAdapter(this).apply {
        }
    }

    override fun initContentView(): Int {
        return R.layout.fragment_sort_choose_list
    }

    override fun initVariableId(): Int {
        return BR.viewModel
    }

    override fun initData() {
        super.initData()
        viewModel.tvTitle.set("物品管理")
        viewModel.storehouseId =
            arguments?.getSerializable(AppConstants.BundleKey.STORE_HOUSE_KEY) as Int?
        initAdapter()
        mAdapter.sortIds = arguments?.getIntegerArrayList("sortIds")
        reload()
    }


    private fun initAdapter() {
        binding.recyclerView.run {
            adapter = mAdapter
        }
    }

    override fun initViewObservable() {
        viewModel.uc.loadCompleteEvent.observe(this) { data ->
            this.loadCompletedData(
                data?.hasNextPage,
                viewModel.currentPage == 2,
                data != null,
                data?.total,
                data?.list,
                mAdapter,
                binding.recyclerView,
                binding.smartCommon
            )
        }
        viewModel.uc.loadCategoryEvent.observe(this) {
            showCategoryPopup(it)
        }
    }

    private fun showCategoryPopup(list: List<CategoryBean>) {
        val pop = CategoryPopup(requireContext()) { it ->
            val name: String? = it?.name
            var ids: List<Int>? = null
            it?.childIds?.let {
                ids = ArrayList<Int>(it)
            }
            binding.btnSelected.text = name
            viewModel.currentPage = 1
            viewModel.getSortList(sortPIdList = ids)
        }
        pop.setList(list)
        XPopup.Builder(context)
            .asCustom(pop)
            .show()
    }

    override fun reload() {
        super.reload()
        binding.smartCommon.autoRefresh()
    }

}